import { Component, ChangeDetectionStrategy, OnInit, Input, ViewChild } from '@angular/core';
import {
  NzModalRef,
  NzMessageService,
  NzDrawerRef,
  NzFormatEmitEvent,
  NzTreeComponent,
  NzNotificationService,
} from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { replaceKeysDeep } from '@shared';

@Component({
  selector: 'role-modal',
  templateUrl: './role-modal.component.html',
})
export class RoleModalComponent implements OnInit {
  @Input()
  record: { [key: string]: any } = {};
  // 部门选择子抽屉显示隐藏开关
  deptsVisible = false;
  // 部门树节点
  nodes = [];
  // 当前自定义选择的数据部门清单
  dsScopes = [];
  defaultSelectedKeys = [];
  // 节点树映射
  mapShortToLong = {
    id: 'key',
    name: 'title',
  };
  searchValue = '';
  @ViewChild('deptTree', { static: false }) deptTree: NzTreeComponent;
  constructor(
    public http: _HttpClient,
    private msg: NzMessageService,
    private ref: NzDrawerRef,
    private notice: NzNotificationService,
  ) {}

  ngOnInit() {
    if (this.record.roleId) {
      this.http.get(`/cf/admin/role/${this.record.roleId}`).subscribe((res: any) => {
        if (res.status === 200) {
          this.record = res.data;
          this.dsScopes = [];
          if (this.record.dsScope) {
            this.record.depts.forEach(r => {
              this.dsScopes.push(r);
            });
          }
        }
      });
    }
  }

  ok() {
    if (this.record.roleId) {
      this.http
        .put(`/cf/admin/role`, this.record)
        .pipe(catchError(err => of(err)))
        .subscribe(res => {
          if (res.status === 200) {
            this.notice.success('成功', '操作成功');
            this.close(true);
          }
        });
    } else {
      this.http
        .post(`/cf/admin/role`, this.record)
        .pipe(catchError(err => of(err)))
        .subscribe(res => {
          if (res.status === 200) {
            this.notice.success('成功', '操作成功');
            this.close(true);
          }
        });
    }
  }

  close(ret = false) {
    if (ret) {
      this.ref.close(ret);
    } else {
      this.ref.close();
    }
  }

  openDepts() {
    this.http
      .get(`/cf/admin/dept/tree`)
      .pipe(catchError(err => of(err)))
      .subscribe(res => {
        if (res.status === 200) {
          this.nodes = [];
          const o: [] = replaceKeysDeep(res.data, this.mapShortToLong);
          o.forEach(r => {
            this.nodes.push(r);
          });
          this.defaultSelectedKeys = [];
          this.dsScopes.forEach(r => {
            this.defaultSelectedKeys.push(r.value);
          });
        }
      });
    this.deptsVisible = true;
  }

  closeDepts() {
    this.deptsVisible = false;
  }

  // 选择了数据部门
  submitDepts() {
    this.dsScopes = [];
    const tmp = [];
    this.deptTree.getCheckedNodeList().forEach(r => {
      this.dsScopes.push({ label: r.origin.title, value: r.origin.key });
      tmp.push(r.origin.key);
    });
    this.record.dsScope = tmp.join(',');
    this.closeDepts();
  }

  nzEvent(event: NzFormatEmitEvent): void {}
}
